package com.example.carpro.utils

import com.blankj.utilcode.util.GsonUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.IOException

const val baseUrl = "http://124.93.196.45:10001"
val client = OkHttpClient()
var token = ""

suspend inline fun <reified T> okRequest(
    url: String,
    requestType: String = "GET",
    map: Map<String, Any> = mutableMapOf(),
    crossinline success: (T) -> Unit
) {
    withContext(Dispatchers.IO) {
        val request = Request.Builder()
            .url(baseUrl + url)
            .method(
                requestType,
                GsonUtils.toJson(map).toRequestBody("application/json".toMediaType()).takeIf {
                    map.keys.isNotEmpty()
                })
            .also {
                if (token.isNotBlank()) it.addHeader("Authorization", token)
            }
            .addHeader("Content-Type", "application/json")
            .build()

        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                e.message.toString().showToast()

            }

            override fun onResponse(call: Call, response: Response) {
                val data = GsonUtils.fromJson(response.body?.string(), T::class.java)
                success(data)
            }
        })
    }

}


